package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsMode;
import com.atguigu.common.utils.Constant;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResp;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Farewell
 * @Date: 2022/6/9 15:23
 * @Description:
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResp search(SearchParam searchParam) {
        SearchRequest request = buildSearchRequest(searchParam);
        try {
            SearchResponse searchResponse = client.search(request, GulimallElasticSearchConfig.COMMON_OPTIONS);
            return buildSearchResponse(searchParam, searchResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        // 属性过滤
        if (!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            List<String> attrs = searchParam.getAttrs();
            for (String attr : attrs) {
                // 每次将属性值组装并放入
                // 编号和值用 _ 分割
                String[] split = attr.split("_");
                // 值之间用 : 分割
                String[] attrValue = split[1].split(":");
                // 设置attrId
                TermQueryBuilder attrIdQuery = QueryBuilders.termQuery("attrs.attrId", split[0]);
                // 设置attrValue
                TermsQueryBuilder attrValueQuery = QueryBuilders.termsQuery("attrs.attrValue", attrValue);
                BoolQueryBuilder boolQueryAttr = QueryBuilders.boolQuery();
                boolQueryAttr.must(attrIdQuery);
                boolQueryAttr.must(attrValueQuery);
                boolQuery.filter(QueryBuilders.nestedQuery("attrs", boolQueryAttr, ScoreMode.None));
            }
        }
        // 分类过滤
        if (!StringUtils.isEmpty(searchParam.getCatalog3Id())) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        // 品牌过滤
        if (!CollectionUtils.isEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        // 价格区间过滤
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            String skuPrice = searchParam.getSkuPrice();
            RangeQueryBuilder skuPriceQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] split = skuPrice.split("_");
            if (skuPrice.startsWith("_")) {
                // 只有最大值
                skuPriceQuery.lte(split[split.length - 1]);
            } else {
                if (skuPrice.endsWith("_")) {
                    // 只有最小值
                    skuPriceQuery.gte(split[0]);
                } else {
                    skuPriceQuery.lte(split[0]);
                    skuPriceQuery.gte(split[1]);
                }
            }
            boolQuery.filter(skuPriceQuery);
        }
        // 库存过滤
        if (searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock().equals(1)));
        }
        sourceBuilder.query(boolQuery);

        // 排序
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            // 前为排序字段, 后为排序条件
            String[] split = searchParam.getSort().split("_");
            sourceBuilder.sort(split[0], Constant.ASC.equalsIgnoreCase(split[1]) ? SortOrder.ASC : SortOrder.DESC);
        }
        // 分页
        sourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PAGE_SIZE);
        sourceBuilder.size(EsConstant.PAGE_SIZE);
        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<b style='color:red'>");
        highlightBuilder.postTags("</b>");
        highlightBuilder.field("skuTitle");
        sourceBuilder.highlighter(highlightBuilder);

        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 品牌子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(50));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(50));
        sourceBuilder.aggregation(brandAgg);
        // 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(50));
        sourceBuilder.aggregation(catalogAgg);
        // 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        // attrId对应的名字
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(50));
        // attrId对应的值
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);

        SearchRequest searchRequest = new SearchRequest(EsConstant.PRODUCT_INDEX);
        searchRequest.source(sourceBuilder);
        System.out.println(sourceBuilder);
        return searchRequest;
    }

    private SearchResp buildSearchResponse(SearchParam searchParam, SearchResponse searchResponse) {
        SearchHits hits = searchResponse.getHits();
        SearchResp searchResp = new SearchResp();
        // 设置商品列表
        SearchHit[] sources = hits.getHits();
        List<SkuEsMode> products = new ArrayList<>();
        if (sources != null && sources.length > 0) {
            for (SearchHit source : sources) {
                String sourceAsString = source.getSourceAsString();
                SkuEsMode skuEsMode = JSON.parseObject(sourceAsString, SkuEsMode.class);
                // 判断高亮
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField skuTitle = source.getHighlightFields().get("skuTitle");
                    // 更新高亮字段
                    skuEsMode.setSkuTitle(skuTitle.getFragments()[0].string());
                }
                products.add(skuEsMode);
            }
        }
        searchResp.setProducts(products);
        // 设置页码
        searchResp.setPageNum(searchParam.getPageNum());
        // 设置总数
        long total = hits.getTotalHits().value;
        searchResp.setTotal(total);
        // 设置总页数
        int totalPages = (int) Math.ceil(1.0 * total / EsConstant.PAGE_SIZE);
        searchResp.setTotalPages(totalPages);
        // 设置品牌列表
        Aggregations aggregations = searchResponse.getAggregations();
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        List<SearchResp.BrandVo> brandVoList = new ArrayList<>();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            SearchResp.BrandVo brandVo = new SearchResp.BrandVo();
            // 设置id
            String brandId = brandAggBucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brandId));
            // 获取子聚集
            Aggregations brandAggBucketAggregations = brandAggBucket.getAggregations();
            // 设置名称
            ParsedStringTerms brandNameAgg = brandAggBucketAggregations.get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            // 设置图片地址
            ParsedStringTerms brandImgAgg = brandAggBucketAggregations.get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVoList.add(brandVo);
        }
        searchResp.setBrands(brandVoList);
        // 设置分类列表
        List<SearchResp.CatalogVo> catalogVoList = new ArrayList<>();
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> catalogAggBuckets = catalog_agg.getBuckets();
        for (Terms.Bucket catalogAggBucket : catalogAggBuckets) {
            SearchResp.CatalogVo catalogVo = new SearchResp.CatalogVo();
            String catalogId = catalogAggBucket.getKeyAsString();
            // 设置编号
            catalogVo.setCatalogId(Long.parseLong(catalogId));
            // 设置分类名
            ParsedStringTerms catalogNameAgg = catalogAggBucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVoList.add(catalogVo);
        }
        searchResp.setCatalogs(catalogVoList);
        // 设置属性
        List<SearchResp.AttrVo> attrVoList = new ArrayList<>();
        ParsedNested attrAgg = aggregations.get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrIdAggBuckets = attrIdAgg.getBuckets();
        for (Terms.Bucket attrIdAggBucket : attrIdAggBuckets) {
            SearchResp.AttrVo attrVo = new SearchResp.AttrVo();
            // 设置id
            long attrId = attrIdAggBucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            // 设置名称
            Aggregations attrIdAggBucketAggregations = attrIdAggBucket.getAggregations();
            ParsedStringTerms attrNameAgg = attrIdAggBucketAggregations.get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            // 设置值
            List<String> attrValues = new ArrayList<>();
            ParsedStringTerms attrValueAgg = attrIdAggBucketAggregations.get("attr_value_agg");
            attrValueAgg.getBuckets().forEach(value -> attrValues.add(value.getKeyAsString()));
            attrVo.setAttrValue(attrValues);
            attrVoList.add(attrVo);
        }
        searchResp.setAttrs(attrVoList);
        // 设置高亮
        return searchResp;
    }
}
